package com.wlr.study.leetcode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author lrwang
 * @version 1.0
 * @date 2022/4/6 23:31
 */
public class LeetCode111 {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        int depth = 0;
        while (!deque.isEmpty()) {
            int size = deque.size();
            depth++;
            for (int i = 0; i < size; i++) {
                TreeNode poll = deque.poll();
                if (poll.left == null && poll.right == null) {
                    // 是叶子结点，直接返回depth，因为从上往下遍历，所以该值就是最小值
                    return depth;
                }
                if (poll.left != null) {
                    deque.offer(poll.left);
                }
                if (poll.right != null) {
                    deque.offer(poll.right);
                }
            }
        }
        return depth;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        TreeNode rootR = new TreeNode(3);
        TreeNode rootRr = new TreeNode(3);
        TreeNode rootRrr = new TreeNode(3);
        TreeNode rootRrrr = new TreeNode(3);
        TreeNode rootRrrrr = new TreeNode(3);
        root.right=rootR;
        rootR.right=rootRr;
        rootRr.right=rootRrr;
        rootRrr.right=rootRrrr;
        rootRrrr.right=rootRrrrr;
        LeetCode111 leetcode111=new LeetCode111();
        System.out.println(leetcode111.minDepth(root));
    }
}
